<template>
    <div class="tables">  
        <!--头部-->
        <slot name="header">
            <div class="page-title">
                <h3>{{title}}</h3>
                <ul class="butns">
                    <li v-for = "(item, index) in butns" :key="index">
                        <div @click = "titleEvent(item.type,item.event,selectedItems,$event)" :class="item.class">
                            <img :src="item.icon" />
                            <span>{{item.name}}</span>
                        </div>
                    </li>
                </ul>
            </div>
        </slot>     
        <!--过滤-->
        <slot name="filter"></slot>
        <!--table-->
        <div class="table_wrap" style="position: relative;" :class="tableStyle">
		    <loading v-if= 'animateShow'></loading>
            <table class="data-table" >
				<thead class="thead-bottom-line">
                    <tr>
                        <template v-for="head_enum in field">
                            <!--选择-->
                            <th v-if="head_enum.type === 'checkbox'" 
                                class="check" 
                                :style="head_enum.style">
                                                          
                                <input type="checkbox" 
                                       @change="toggleAllCheck(collectField)" 
                                       :checked="checkCheckboxesState(field.name)">
                            </th>
                            <!--排序-->
                            <th v-else-if="head_enum.type === 'rank'" 
                                class="rank" 
                                :style="head_enum.style">

                                {{head_enum.label ? head_enum.label : $t('common.tableIndex')}} 
                            </th>
                            <!--操作-->
                            <th v-else-if="head_enum.type === 'opration'" 
                                :style="head_enum.style">

                                {{$t('common.tableOper')}}
                            </th>
                           
                            <th v-else :style="rankable ? 'cursor:pointer' : head_enum.style" 
                                @click="theadEvent(head_enum.name)"
                                @mouseenter="icon_show = head_enum.name" 
                                @mouseleave="icon_show=''">

                                {{head_enum.label}}
                                <template v-if="rankable">
                                    <img v-if="orderby === head_enum.name && order === 'asc'" 
                                        class="i_pic" 
                                        :src="`/static/${themeColor}-img/up.png`">
						            <img v-if="orderby === head_enum.name && order ==='desc' || (icon_show===head_enum.name && orderby!=head_enum.name)" 
                                        class="i_pic" 
                                        :src="`/static/${themeColor}-img/down.png`">
                                </template>                                
                            </th>
                        </template>
					</tr>
				</thead>
				<transition name="fade" mode ="out-in">
                    <tbody v-if='!animateShow'>                      
                        <tr v-for="(item, index) in data" 
                            :key="index" 
                            @click="toggleCheck(item, collectField)" 
                            @dblclick="dbPreTreat(item, collectField)" >
                            <template v-if="index < tableData.length">
                                <template v-for="field_enum in field">
                                    <!--选择-->
                                    <td v-if="field_enum.type === 'checkbox'">                                    
                                        <input type="checkbox" :checked="rowSelected(item, collectField)">
                                    </td>
                                    <!--排序-->
                                    <td v-else-if="field_enum.type === 'rank'">{{(index + 1) + perNum * (curpage - 1)}}</td>
                                    <!--操作-->
                                    <td v-else-if="field_enum.type === 'opration'">
                                        <button 
                                          class="button button--aylen" 
                                          :class ="item[field_enum.linkname] ? 'unblock' : 'block'"
                                          @click="tableBtnEvent(field_enum.event, item[field_enum.linkname], item[field_enum.collectname])">

                                          {{item[field_enum.linkname] ? field_enum.label[0] : field_enum.label[1]}}
                                        </button>                           
                                    </td>
                                     <!--备注-->
                                    <td v-else-if="field_enum.editable" 
                                        @mouseenter="hoverEvent($event)" 
                                        @mouseleave="leaveEvent" 
                                        style="position: relative;min-width: 80px;">
                                        <input 
                                            v-if="show_input==index" 
                                            class="text_input" 
                                            type="text" 
                                            v-model="item[field_enum.name]"
                                            :val="item[field_enum.name]"  
                                            @blur="editDesc(item,$event)">                                        
                                        <span v-else style="display:in-lineblock;padding: 0 10px;">
                                             {{item[field_enum.name] ? item[field_enum.name] : '-'}}
                                        </span> 
                                        <img 
                                            v-if="!item.mac.includes('.')" 
                                            class="edit_img" 
                                            :src="`/static/${themeColor}-img/descedit.png`" 
                                            @click="showInput(index, item[field_enum.name])">
                                        <p v-if="show_input == index && desc_error" style="color: #dc3434;max-width: 300px;">{{desc_error}}</p>              
                                    </td>
                                    <!--slot-->
                                    <td  v-else-if="field_enum.type === 'detail'" 
                                        class="detail" 
                                        @mouseenter="showIt(index, item)" 
                                        @mouseleave="hide(index)">
                                        <span>.....</span>
                                        <div class="detail_wrap ">
                                            <div class="d_content" :class="index > 20 ? 'last_detail' : 'detal_tabel'">
                                                <div class="ower">
                                                    <span>MAC：{{item.mac ? item.mac : '-'}}</span>
                                                    <span style="margin-left: 10px;">{{$t('common.tableNote')}}{{item.description ? item.description : '-'}}</span>
                                                </div>
                                                <div v-if='!detailshow' style="position: relative;height: 100px;background:#fff;z-index: 20;width: 456px;">
                                                    <loading></loading>
                                                </div>
                                                <table v-else class="style_b">
                                                    <thead>
                                                        <tr> 
                                                            <th style="width: 60px;">{{$t('common.tableIndex')}}</th>
                                                            <th>{{$t('common.tableTh1')}}</th>
                                                            <th>{{$t('common.tableTh2')}}</th>
                                                        </tr>
                                                    </thead>
                                                    <tbody>
                                                        <tr v-for="(val, i) in detailDatas">
                                                            <td>{{i + 1}}</td><td>{{val.vip ? val.vip : '-'}}</td><td>{{val.vary_time ? val.vary_time : '-'}}</td>
                                                        </tr>
                                                    </tbody>																		
                                                </table>
                                            </div>	
                                            <img  :src="`/static/${themeColor}-img/toright.png`" />
                                        </div>
                                    </td>  
                                    <!--超出省略号-->
                                    <td 
                                        v-else-if="field_enum.ellipsis" 
                                        :style="field_enum.ellipsis" 
                                        style="padding-left:10px;padding-right:10px;">
                                        <p :title="item[field_enum.name]" style="white-space:nowrap; overflow:hidden; text-overflow:ellipsis;">
                                            {{item[field_enum.name] ? item[field_enum.name] : '-'}}
                                        </p>
                                    </td>     
                                    <!--普通-->
                                    <td v-else :style="field_enum.style">
                                       <span :style="item.style">{{String(item[field_enum.name]) && item[field_enum.name] !== null && item[field_enum.name] !== undefined ? item[field_enum.name] : '-'}}</span>
                                    </td>
                                </template>
                            </template>
                            <template v-else>
                                 <td v-for="item in field">&nbsp;</td>      
                            </template>                          
                        </tr>
                    </tbody>
				</transition>
			</table>
            <p class="tableNotice">{{tableNotice}}</p> 
       </div>
       <!--分页-->
       <pagination 
            v-if='show' 
            :totalNum='totalNum' 
            :nowpage='curpage'
            @curPage ="curPageEvent" 
            :pageSize='pageSize' 
            @changePageSize='changePageSize'>
        </pagination>
    </div>
</template>
<script>
    import loading from './loading'
    import pagination from './pagination'
    import defendService from 'services/defendService'
    import logManageService from 'services/logManageService'
    export default {
        props: {
            title: {
                type:String
            },
			butns: {
				type: Array
			},
            field: {
                type: Array
            },
            tableData: {
                type: Array
            },
            totalNum: {
                type:Number
            },
            collectField: {
                type:String
            },
            tableNotice: {
                type:String
            },
            rankable: {
                type:Boolean
            },
            animateShow: {
                type:Boolean
            },
            tableName: {
                type:String
            },
            pageSize: {
               type: Array 
            },
            curPage: {},
            tableStyle: {},
            checkedItems: {},
            dbClickDisabled: {},
            clearSelectItems: {},
            clearSelectItem1: {},
            tdWidth: {}
		},
		components: {
            loading,
            pagination
		},
        watch: {
            clearSelectItems() {
                this.selectedItems = this.clearSelectItems
            },
            clearSelectItem1() {
                this.selectedItem1 = this.clearSelectItem1
            },
            checkedItems() {
                if (this.checkedItems.length > 0) {
                   this.selectedItems = this.checkedItems.split(',')
                }
            },
            selectedItems() {
                this.$emit('sentSelectedItems',this.selectedItems)
            },
            selectedItem1() {
                this.$emit('sentSelectedItem1',this.selectedItem1)
            },
            curPage() {
                this.curpage = this.curPage
            }
        },
        computed:{
            data() {
                let data = []
                for(let i = 0; i < this.perNum; i++) {
                    data = [...data,{}]
                }
                for(let i = 0; i < this.tableData.length; i++) {
                    data[i] = this.tableData[i]
                }
                return data
            }
        },
        data() {
            return{
                show: true,
                curpage: 1,  
                perNum: 10,    
                error_notice: false,
                selectedItems:this.checkedItems ? this.checkedItems.split(',') : [],
                type: '',
                params: {},
                error_msg: "",
                edit_data: {},
                format_error_arr: [],
                Index_show: null,
                icon_show: '',
                orderby: 'con',
                order: 'desc',
                selectedItem1: [],
                detailDatas: [],
				detailshow: false,
                show_input: null,
                desc_error: '',
                // old_desc: ''
            }
        },
        methods:{  
            changePageSize (pageSize) {
                this.perNum = pageSize
                let totalPage =  Math.ceil(this.totalNum / pageSize)
                if (totalPage < this.curpage){
                    if (totalPage === 0) {
                        this.curPage = 1
                    } else {
                        this.curpage = totalPage
                    }
                }
                this.$emit('changePageSize', this.curpage, pageSize, this.tableName)
            },
            titleEvent(type, eventname, val, event) { 
                if (type === "add") {             
                    this.addEvent()
                } else if (type === "edit") {
                    this.editEvent(event)
                } else if (type === "del") {
                    this.delEvent(event)
                } else {
                    this.$emit(eventname,val)
                }
                this.$emit('reset', type, this.tableName)
            },  
            addEvent() {     
                this.$emit("sentEditData",{})//重置数据
                $('#modal').modal('show');
            },
            delEvent(event) {
                let ele = $(event.currentTarget)
                let select_arr_name = this.selectedItems.length
                if (this.tableName && (this.tableName.indexOf('no') >= 0)) {
                     select_arr_name = this.selectedItem1.length
                }
                if (select_arr_name <= 0) {                          
                    this.popoverShow(ele,this.$t('common.tableDelNotice'))
                } else {                          
                    $('#modal').modal('show');
                }
            },
            editEvent(event) {
                let ele = $(event.currentTarget)
                let select_arr_name = this.selectedItems
                if (this.tableName&&(this.tableName.indexOf('no') >= 0)) {
                     select_arr_name = this.selectedItem1
                }
                if (select_arr_name.length <= 0) {  
                    this.popoverShow(ele,this.$t('common.tableModNotice'))
                } else if (select_arr_name.length > 1) {
                    this.popoverShow(ele,this.$t('common.tableModMoreNotice'))
                } else if (select_arr_name.length === 1) {                        
                    let edit_data = this.tableData.filter((item) => {
                        if (item[this.collectField] == select_arr_name[0]) { return item;}
                    })[0]
                    this.edit_data = JSON.parse(JSON.stringify(edit_data))//深拷贝
                    this.$emit("sentEditData",this.edit_data)
                    $('#modal').modal('show');
                }   
            }, 
            theadEvent(name) {
                this.icon_show =''
                if (this.orderby === name) {//换排序
                    this.order = this.order ==='desc'?'asc':'desc'
                } else {//第一次
                    this.order= 'desc'
                }		   
                this.orderby = name
                let params = {
                    by: this.orderby,
                    order: this.order,
                    road: 'null'
                }
                this.$emit('rankData', params, this.tableName)
            },            
            tableBtnEvent(eventname, status, operid) {
                this.$emit(eventname, status, operid)
            },       
            hoverEvent(event) {
                $(event.currentTarget).find('.edit_img').fadeIn(100)
            },
            leaveEvent() {
                $('.edit_img').fadeOut(100)
            },   

            showInput(index, desc) {
                this.show_input = index
                this.desc_error = ""    
                this.$emit('clearInterval', true)
                setTimeout(() => {
                    $('.text_input').focus()
                },10)
            },
            editDesc(old_item, event) {//快速修改备注名
                let new_desc = $(event.currentTarget).val()
                
				let descdata = {
					mac: old_item.mac,	
					desc: new_desc,
					gid: 0
				}
               let sendData = `${old_item.mac}|${new_desc}`
				defendService.setDesc({3: sendData})
				.then((res)=>{
					if (res.errcode === 0) {                  
                        this.show_input =null
                        this.desc_error = ""
                        this.params.oper='load'
                        this.params.page=this.curpage
                        this.$emit('clearInterval',false)
                        this.$emit('loadData',this.params)  
                    } else {
                        this.desc_error = res.errorMessage
                    }
				})
			},
            showIt(index,item) {
				clearTimeout(this.moveTime)
				this.moveTime = setTimeout(()=>{				
					this.recvDetailDate(item)
					$('.detail_wrap').eq(index).fadeIn(200)					
				},200)					
			},
			recvDetailDate(item) {
                this.detailshow = false
				logManageService.getDetail(item.id)
				.then((res)=>{
					this.detailshow = true
					if (res.errcode === 0) {		
						this.detailDatas=res['6'].logs
					}
				})
			},
			hide(index) {					
				clearTimeout(this.moveTime)
				$('.detail_wrap').eq(index).fadeOut(200)
			},
            dbPreTreat(Item,name) {
                 let item_length = 0
                 for (let [k, v] of Object.entries(Item)) {
                   item_length++
                 }
                if (item_length<=0||this.dbClickDisabled==true) {
                    return
                } 
                this.type = "edit"           
                this.selectedItems = []
                this.selectedItems.push(Item[name])
                this.edit_data =JSON.parse(JSON.stringify(Item))//深拷贝 
                this.params = this.edit_data
                $('#modal').modal('show'); 
                this.$emit('reset',this.type,this.tableName)
                this.$emit("sentEditData",this.edit_data)                     
            },             
            toggleAllCheck(name) {
                if (this.tableName && (this.tableName.indexOf('no') >= 0)) {
                    if (this.tableName && this.selectedItem1.length < this.tableData.length) {
                        this.selectedItem1 = this.tableData.map(function(item) {
                            return item[name]
                        })
                    } else {
                        this.selectedItem1 = []
                    }
                } else {
                    if (this.selectedItems.length < this.tableData.length) {
                        this.selectedItems = this.tableData.map(function(item) {
                            return item[name]
                        })
                    } else {
                        this.selectedItems = []
                    }
                }
                
            },
            toggleCheck(item, name) {
                if (!item[name]) {
                    return
                }   
                if (this.tableName && (this.tableName.indexOf('no') >= 0)) {
                    let index = this.selectedItem1.indexOf(item[name])
                    if (index >= 0) {
                        this.selectedItem1.splice(index,1)
                        return false
                    } else {
                        this.selectedItem1.push(item[name])
                        return true
                    }
                } else {
                    let index = this.selectedItems.indexOf(item[name])
                    if (index >= 0) {
                        this.selectedItems.splice(index,1)
                        return false
                    } else {
                        this.selectedItems.push(item[name])
                        return true
                    }
                }     
                	
            },
            checkCheckboxesState() {
                if (this.tableName&&(this.tableName.indexOf('no')>=0)) {
                   if (this.selectedItem1.length === this.tableData.length
                    &&this.selectedItem1.length != 0) {
                        return true
                    }
                } else {
                    if (this.selectedItems.length === this.tableData.length
                    &&this.selectedItems.length != 0) {
                        return true
                    }
                }     
                
            },
            rowSelected(Item,name) {
                if (this.tableName&&(this.tableName.indexOf('no')>=0)) {
                    return this.selectedItem1.indexOf(Item[name]) >= 0
                } else {
                    return this.selectedItems.indexOf(Item[name]) >= 0
                }     
               
            },
            curPageEvent(cur_page) {//分页
                this.curpage = cur_page
                this.type = "page_change"   
                this.$emit('reset', this.type, this.tableName)
                this.$emit('changePageSize', this.curpage, this.perNum, this.tableName)                  
            },
            popoverShow(ele,content) {//删除弹窗
				$(ele).attr({
					'data-toggle': 'popover',
                    'data-placement':"bottom",
					'data-content': content
				}).popover('show')
				setTimeout(function() {
					$(ele).popover('destroy')
				}, 1500)
			}
        }
    }

</script>
